package chan.project.smartlaweveryman.controller;


import chan.project.smartlawcommon.annotation.AuthCheck;
import chan.project.smartlawcommon.common.BaseResponse;
import chan.project.smartlawcommon.common.DeleteRequest;
import chan.project.smartlawcommon.common.ErrorCode;
import chan.project.smartlawcommon.common.ResultUtils;
import chan.project.smartlawcommon.constant.UserConstant;
import chan.project.smartlawcommon.exception.BusinessException;
import chan.project.smartlawcommon.exception.ThrowUtils;
import chan.project.smartlaweveryman.mapper.ChatMessagesMapper;
import chan.project.smartlaweveryman.service.ChatMessagesService;
import chan.project.smartlaweveryman.service.impl.UserInfoServiceImpl;
import chan.project.smartlawmodel.dto.common.CommonInfoRegisterRequest;
import chan.project.smartlawmodel.dto.lawyer.LawyerInfoRegisterRequest;
import chan.project.smartlawmodel.dto.user.*;
import chan.project.smartlawmodel.entity.ChatMessages;
import chan.project.smartlawmodel.entity.LawyerInfo;
import chan.project.smartlawmodel.entity.UserInfo;
import chan.project.smartlawmodel.enums.UserRoleEnum;
import chan.project.smartlawmodel.vo.LoginUserVO;
import chan.project.smartlawmodel.vo.UserInfoVO;
import chan.project.smartlaweveryman.service.UserInfoService;
import chan.project.smartlawservice.commonService.CommonInfoFeignClient;
import chan.project.smartlawservice.lawyerService.LawyerInfoFeignClient;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;



/**
 * 用户信息接口，用于管理用户的登录登出
 *
 * @author <a href="https://github.com/kavansp">kavansp</a>
 * 
 */
@Tag(name = "用户信息接口")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserInfoController {

    @Resource
    private UserInfoService userService;

    /**
     * 普通用户注册
     *
     * @param commonInfoRegisterRequest
     * @return
     */
    @PostMapping("/register/common")
    public BaseResponse<Long> userRegister(@RequestBody CommonInfoRegisterRequest commonInfoRegisterRequest) {
        if (ObjectUtil.isEmpty(commonInfoRegisterRequest)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = commonInfoRegisterRequest.getUserAccount();
        String userPassword = commonInfoRegisterRequest.getUserPassword();
        String checkPassword = commonInfoRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.commonRegister(commonInfoRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 律师用户注册
     */
    @PostMapping("/register/lawyer")
    public BaseResponse<Long> lawyerRegister(@RequestBody LawyerInfoRegisterRequest lawyerInfoRegisterRequest) {
        if (lawyerInfoRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = lawyerInfoRegisterRequest.getUserAccount();
        String userPassword = lawyerInfoRegisterRequest.getUserPassword();
        String checkPassword = lawyerInfoRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.lawyerRegister(lawyerInfoRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        UserInfo user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     * @param userAddRequest
     * @param request
     * @return
     */
    @Deprecated
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserInfoAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInfo user = new UserInfo();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((UserInfoServiceImpl.SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserInfoUpdateRequest userUpdateRequest,
            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInfo user = new UserInfo();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<UserInfo> getUserById(@RequestParam("id") long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInfo user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserInfoVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<UserInfo> response = getUserById(id, request);
        UserInfo user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserInfo>> listUserByPage(@RequestBody UserInfoQueryRequest userQueryRequest,
            HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<UserInfo> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserInfoVO>> listUserVOByPage(@RequestBody UserInfoQueryRequest userQueryRequest,
            HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<UserInfo> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserInfoVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserInfoVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserInfoUpdateMyRequest userUpdateMyRequest,
            HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInfo loginUser = userService.getLoginUser(request);
        UserInfo user = new UserInfo();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 使用JWT进行普通用户登录验证
     * @param userLoginRequest
     * @return
     */
    @PostMapping("/login/common")
    private BaseResponse<LoginUserVO> jwtLogin(@RequestBody UserLoginRequest userLoginRequest) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.commonUserLogin(userAccount, userPassword);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 使用JWT进行律师用户登录验证
     * @param userLoginRequest
     * @return
     */
    @PostMapping("/login/lawyer")
    private BaseResponse<LoginUserVO> jwtLoginLawyer(@RequestBody UserLoginRequest userLoginRequest) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.lawyerUserLogin(userAccount, userPassword);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 管理员角色登录（主要用于数据管理平台进行登录）
     * @param adminLoginQuery
     * @return
     */
    @PostMapping("/login/admin")
    private BaseResponse<LoginUserVO> jwtLoginAdmin(@RequestBody AdminLoginQuery adminLoginQuery) {
        if (adminLoginQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = adminLoginQuery.getUserAccount();
        String userPassword = adminLoginQuery.getUserPassword();
        String userRole = adminLoginQuery.getUserRole();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.baseUserLogin(userAccount, userPassword,userRole);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户身份转换(用于用户身份的转换，例如律师与普通用户之间进行转换)
     */
    @GetMapping("/change/permission")
    public BaseResponse<String> changeUserPermission(@RequestParam("userRole") String userRole){
        if(StringUtils.isEmpty(userRole)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取当前登录用户的角色
        String role = (String) StpUtil.getExtra("role");
        if(role.equals(userRole)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"当前已是该用户，无法切换");
        }
        if(userRole.equals(UserRoleEnum.SUPER_ADMIN.getValue()) || userRole.equals(UserRoleEnum.DATA_ADMIN.getValue())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"只能同级转换账号");
        }
        StpUtil.logout();
        StpUtil.login(StpUtil.getLoginId(),userRole);
        return ResultUtils.success("切换成功");
    }

    @Resource
    private ChatMessagesService chatMessagesService;

    @Resource
    private ChatMessagesMapper chatMessagesMapper;

    @GetMapping("test")
    private String test(){
        ChatMessages chatMessages = new ChatMessages();
        chatMessages.setSenderId(8L);
        chatMessages.setReceiverId(8L);
        chatMessages.setMessageText("HELLO");
        int insert = chatMessagesMapper.insert(chatMessages);
        return "test";
    }
}
